package com.xk._02算法篇._01sort.sort.cmp;

import com.xk._02算法篇._01sort.sort.Sort;
import com.xk.tools.Integers;

/**
 * @description: 选择排序：最小的元素放在最左边
 * @author: xu
 * @date: 2022/10/1 4:34
 */
public class SelectionSort1<E extends Comparable<E>> extends Sort<E> {
    /**
     * 选择排序：最大的元素放在最右边
     */
    private void selectionSort1() {
        for (int end = array.length - 1; end > 0; end--) {
            int maxIndex = 0;
            for (int begin = 1; begin <= end; begin++) {
                if (cmp(maxIndex, begin) <= 0) {
                    // <= : 为了算法的稳定性
                    // 从前往后遍历，将相等数值的最后一个放到数组的最后面去
                    maxIndex = begin;
                }
            }
            swap(maxIndex, end);
        }
    }

    @Override
    protected void sort() {
        selectionSort1();
    }

    public static void main(String[] args) {
        Integer[] array1 = Integers.random(20, 1, 100);
        Integers.println(array1);

        Sort<Integer> selectionSort = new SelectionSort1<>();
        selectionSort.sort(array1);
        System.out.println(selectionSort);
        Integers.println(array1);
        System.out.println("Integers.isAscOrder(array1) = " + Integers.isAscOrder(array1));
    }
}
